﻿using Century.Business.CMS;
using Century.EnterpriseLibrary.Configuration;
using Century.EnterpriseLibrary.GeoIP;
using Century.Model.CMS;
using Century.Web.UI.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;


namespace Century.Web.UI
{
    public class RequestManager
    {
        private static ISiteService siteService = new SiteService();
        public static void CheckUserRequest(HttpRequest request)
        {
            RedirectToTrueSite(request);
        }

        /// <summary>
        /// Method to parse url and redirect user to the true website and 
        /// also set the cookies
        /// </summary>
        /// <param name="request"></param>
        private static void RedirectToTrueSite(HttpRequest request)
        {
            //Check ignore urls such as styles and scripts
            foreach (string ignorePath in ConfManager.Instance.CookieManager.IgnoreUrlList)
            {
                if (!string.IsNullOrEmpty(ignorePath) && request.Url.AbsoluteUri.ToLower().Contains(ignorePath.ToLower()))
                {
                    return;
                }
            }
            string url = request.Url.AbsoluteUri;

            UrlParser parsedURL = new UrlParser(url);
            if (!parsedURL.CurrentAddress.EndsWith("/"))
            {
                HttpContext.Current.Response.Redirect(parsedURL.CurrentAddress+"/");
            }
            //check for separate sites
            if (ConfManager.Instance.CookieManager.SeparateSitesProperties.ConfigValue.Contains(parsedURL.Domain.ToLower()))
            {
                List<string> separateDomains = ConfManager.Instance.CookieManager.SeparateSites;
                string cookieValue = separateDomains.Find(c => c.ToLower().Contains(parsedURL.Domain.ToLower())).Split(':')[1];
                CookieManager.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName, cookieValue);
                if (string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName].Value)
                     || HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName].Value.ToLower() != cookieValue.ToLower())
                {
                    HttpContext.Current.Response.Redirect(parsedURL.CurrentAddress + parsedURL.PathAndQuery);
                }
                return;

            }
            if (string.IsNullOrEmpty(parsedURL.SiteAddress))
            {
                //parsedURL.CleanURL.Replace(
                string siteAddress = string.Empty;
                string sitePath = GetSiteForCurentUser(request, parsedURL, out siteAddress);
                CookieManager.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName, sitePath);
                HttpContext.Current.Response.Redirect(siteAddress + parsedURL.PathAndQuery);
            }
            else
                if (
                         parsedURL.CurrentAddress.ToLower().Replace("www.", string.Empty).Replace("https://", string.Empty).Replace("http://", string.Empty).Replace(":443", string.Empty)
                         !=
                         parsedURL.SiteAddress.ToLower().Replace("www.", string.Empty).Replace("https://", string.Empty).Replace("http://", string.Empty).Replace(":443", string.Empty)
                     )
                {
                    // for https requests
                    if (parsedURL.Host != "localhost")
                    {
                        string newAddress = parsedURL.SiteAddress.Replace("http", parsedURL.Protocol);
                        HttpContext.Current.Response.Redirect(newAddress + parsedURL.PathAndQuery);
                    }
                    CookieManager.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName, parsedURL.SitePath);
                }
                else
                {
                    CookieManager.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName, parsedURL.SitePath);

                    if (string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName].Value)
                   || HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName].Value.ToLower() != parsedURL.SitePath.ToLower())
                    {
                        HttpContext.Current.Response.Redirect(parsedURL.CurrentAddress + parsedURL.PathAndQuery);
                    }
                }


        }

        /// <summary>
        /// Find site for current user
        /// </summary>
        /// <param name="request"></param>
        /// <param name="parsedURL"></param>
        /// <param name="siteAddress"></param>
        /// <returns></returns>
        private static string GetSiteForCurentUser(HttpRequest request, UrlParser parsedURL, out string siteAddress)
        {
            //Get country code by user ip;
            string countryCode = GeoIPService.instance.GetCountryCode(request.UserHostAddress);
            string sitePath = countryCode;

            if (string.IsNullOrEmpty(sitePath))
            {
                //go to global fsa site if ip not find
                Site defaultSite = parsedURL.Sites.Find(c => c.IsDefault);
                sitePath = defaultSite.Path;
                siteAddress = defaultSite.SiteAddress;
            }
            else
            {
                //Find country from county table by geo ip country code

                Site site = parsedURL.Sites.Find(c => c.ContryCode.ToLower() == countryCode.ToLower());
                if (site == null)
                {
                    Site defaultSite = parsedURL.Sites.Find(c => c.IsDefault);
                    sitePath = defaultSite.Path;
                    siteAddress = defaultSite.SiteAddress;
                }
                else
                {
                    sitePath = site.Path;
                    siteAddress = site.SiteAddress;
                }
            }
            return sitePath;
        }


    }
}
